#pragma once
#include <iostream>
#include <memory>
#include "Epoller.hpp"
#include "Socket.hpp"
#include "Common.hpp"
#include "Connection.hpp"
#include "Channel.hpp"
const uint16_t defaultport = -1;
class Listener : public Connection
{
    public:
    Listener(int port = defaultport)
    :_port(port)
    ,_listensock(make_unique<TcpSocket>())
    {
        _listensock->BuildTcpSocketMethod(_port);
        SetNoBlock(_listensock->GetListensockfd());
        SetEvents(EPOLLIN | EPOLLET);
    }
    void Recver() override
    {
        INETADDR client;
        // 新连接就绪了，你能保证只有 一个连接到来吗？ 一次把所有的连接全部获取上来
        // while, ET, sockfd设置为非阻塞！！ ---- listensock本身设置为非阻塞
        while(true)
        {
            int sockfd = _listensock->Accept(&client);
            if(sockfd == ACCEPT_ERR)
                break;
            else if(sockfd == ACCEPT_CONTINUE)
                continue;
            else if(sockfd == ACCEPT_DONE)
                break;
            else
            {
                // 我们获得的是一个合法的fd，普通的文件描述符
                shared_ptr<Connection> conn = make_shared<Channel>(sockfd, client);
                conn->SetEvents(EPOLLIN|EPOLLET);
                if(_handler != nullptr)
                    conn->RegisterHandler(_handler);
                GetOwner()->AddConnection(conn);
            }
        }
    }
    void Sender() override
    {
    }
    void Excepter() override
    {
    }
    int GetFd() override
    {
        return _listensock->GetListensockfd();
    }
    ~Listener(){}
    private:
    int _port;
    unique_ptr<Socket> _listensock;

};